package com.suzhiliang.springbootlesson.securityOAuth2;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.StandardPasswordEncoder;
import org.springframework.security.oauth2.provider.expression.OAuth2MethodSecurityExpressionHandler;


/**
 * Copyright (C), 2015-2019, XXX有限公司
 *
 * @ClassName: SecurityConfiguration
 * @Author: xmm
 * @Date: 2019/7/22 16:10
 * @Description: SpringSecurity配置
 * Spring-security对用户身份进行认证授权：
 * 主要作用是对用户身份通过用户名与密码的方式进行认证并且授权。
 * @Version 1.0
 */
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    //注入用户service
    @Autowired
    private SzlUserDetailsService szlUserDetailsService;


    @Autowired
    public void configure(AuthenticationManagerBuilder builder) throws Exception{
        //设置userService
        builder.userDetailsService(szlUserDetailsService);
    }

    //排除/hello路径拦截
    @Override
    public void configure(HttpSecurity http) throws Exception {
        //定义安全配置，定义/hello不需要安全验证
        http.authorizeRequests()
                .antMatchers("/hello").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .permitAll()
                .and()
                .csrf().disable();          // 关闭csrf防护
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}
